package com.webmall.servlet.pages;

import com.webmall.entity.CateEntity;
import com.webmall.entity.ProdEntity;
import com.webmall.service.webmall_CateDao;
import com.webmall.service.webmall_ProdDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/selectProDetail")
public class selectProDetail extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<CateEntity> fatherList = webmall_CateDao.showCate("father");
        request.setAttribute("fatherList",fatherList);

        ArrayList<CateEntity> childList = webmall_CateDao.showCate("child");
        request.setAttribute("childList",childList);

        String id = request.getParameter("id");

        //*******获取最近访问
        HttpSession session = request.getSession();

        ArrayList<String> ids =(ArrayList<String>)session.getAttribute("ids");
        //1-先判断是不是空的 空的话 声明
        if (ids == null){
            ids = new ArrayList<String>();
        }
        //2--判断大小是否满足,超过长度 移除第一个
        if (ids.size()>= 5){
            ids.remove(0);
        }
        //3 在存在arraylist并且不包含该id时
        if (ids !=null && (!ids.contains(id))){
            ids.add(id);

        }
        session.setAttribute("ids",ids);//设置session、
        ids =(ArrayList<String>)session.getAttribute("ids");
        ArrayList<ProdEntity> history_list = new ArrayList<>() ;//用来存放所有历史记录的prod
        if (ids != null){
            for (int i=0;i<ids.size();i++){
                history_list.add(webmall_ProdDao.selectByCATEId(2,ids.get(i)).get(0));
            }
            System.out.println(history_list.size());
            request.setAttribute("history_list",history_list);
        }

        if (null != id){//自身id
            ArrayList<ProdEntity> plist = webmall_ProdDao.selectByCATEId(2,id);
            request.setAttribute("p",plist.get(0));

            //获取推荐类
            if (null !=plist.get(0)){
                ArrayList<ProdEntity> commend_list = webmall_ProdDao.selectByCATEId(1,String.valueOf(plist.get(0).getPRODUCT_CID()));
                request.setAttribute("commend_list",commend_list);
                //获取所在子分类
                CateEntity c_cate = webmall_CateDao.selectById(String.valueOf(plist.get(0).getPRODUCT_CID()));
                if (c_cate.getCATE_PARENT_ID() !=0){
                    CateEntity f_cate = webmall_CateDao.selectById(String.valueOf(c_cate.getCATE_PARENT_ID()));
                    request.setAttribute("f_cate",f_cate);
                }
                request.setAttribute("c_cate",c_cate);
            }
        }


        request.getRequestDispatcher("proDetail.jsp").forward(request,response);

    }
}
